//
//  RootViewController.m
//  UUChatTableView
//
//  Created by shake on 15/1/4.
//  Copyright (c) 2015年 uyiuyao. All rights reserved.
//

#import "ChatRoomViewController.h"
#import "UUInputFunctionView.h"
#import "UUMessageCell.h"
#import "ChatModel.h"
#import "UUMessageFrame.h"
#import "UUMessage.h"
#import "UUChatCategory.h"
#import <JMessage/JMessage.h>
#import "JCHATStringUtils.h"
#import "JCHATSendMsgManager.h"
#import "GroupInfoViewController.h"
#import "GroupActiveDetailViewController.h"
#import "TopicDetailViewController.h"
#import "EmojiCollectionViewCell.h"
#import "MainNavigationController.h"
#import "PersonalViewController.h"

@interface ChatRoomViewController ()<UUInputFunctionViewDelegate, UUMessageCellDelegate, UITableViewDataSource, UITableViewDelegate,JMessageDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
	CGFloat _keyboardHeight;
    UIImagePickerController *_imagePickerController;
}
@property (strong, nonatomic) ChatModel * chatModel;

@property (strong, nonatomic) UITableView *chatTableView;

@property (strong, nonatomic) UUInputFunctionView *inputFuncView;

@property (nonatomic, assign) int pageNum;

@property (nonatomic, weak)UIButton * rightButton;

@property (nonatomic, copy)NSString * gid;

@property (nonatomic, copy)NSString * is_banned;

@property (nonatomic, weak)UIView * topBackView;
@property (nonatomic, weak)UIImageView * topImageView;
@property (nonatomic, weak)UIImageView * bottomImageView;
@property (nonatomic, weak)UIButton * topCloseButton;
@property (nonatomic, weak)UIButton * bottomCloseButton;
@property (nonatomic, weak)UIButton * topBackButton;
@property (nonatomic, weak)UIButton * bottomBackButton;
@property (nonatomic, weak)UIView * lineView;
@property (nonatomic, weak)UILabel * topTitleLabel;
@property (nonatomic, weak)UILabel * bottomTitleLabel;
@property (nonatomic, weak)UILabel * topShowLabel;
@property (nonatomic, weak)UILabel * bottomShowLabel;
@property (nonatomic, weak)UILabel * topSubLabel;
@property (nonatomic, strong)NSMutableDictionary * muDict;
@property (nonatomic, copy)NSString * activityID;
@property (nonatomic, copy)NSString * topicID;

@property (nonatomic, strong)UIAlertController * alertVC;
//@property (nonatomic, copy)NSString * type;
@property (nonatomic, strong)NSArray * arrEmotion;
@property (nonatomic, weak)UICollectionView * collectionView;
@property (nonatomic, copy)NSString * showEmjio;

@property (nonatomic, assign)BOOL isCanSideBack;
@property (nonatomic, copy)NSString * user_id;

@end

//将数字转为
#define EMOJI_CODE_TO_SYMBOL(x) ((((0x808080F0 | (x & 0x3F000) >> 4) | (x & 0xFC0) << 10) | (x & 0x1C0000) << 18) | (x & 0x3F) << 24);

@implementation ChatRoomViewController

#pragma mark - life circle

- (void)viewDidLoad {
    [super viewDidLoad];
// self.nameLabel.text = conversation.title;
    
    self.pageNum = 10;
    self.showEmjio = @"hidden";
//    self.type = @"reveced";
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = NO;
    
    [self setupNav];
    [self initBasicViews];
    [self addRefreshViews];
    [self loadBaseViewsAndData];
    [self addDelegate];
    [self setupAlertVC];
    [self.conversation clearUnreadCount];
    [self loadData];
    [self setupTopView];
    self.muDict = [NSMutableDictionary dictionaryWithCapacity:2];
    _chatTableView.frame = CGRectMake(0, 0, self.view.uu_width, self.view.uu_height - 40 * SCREENH6 - kBarHeight);
	_inputFuncView.frame = CGRectMake(0, _chatTableView.uu_bottom, self.view.uu_width, 40 * SCREENH6);
    
    
    [self setupCollectionView];
    //获取数组
    self.arrEmotion = [self defaultEmoticons];
}


- (void)setArrEmotion:(NSArray *)arrEmotion{
    
    _arrEmotion = arrEmotion;
    
    [self.collectionView reloadData];
}


//获取默认表情数组
- (NSArray *)defaultEmoticons {
    NSMutableArray *array = [NSMutableArray new];
    for (int i=0x1F600; i<=0x1F64F; i++) {
        if (i < 0x1F641 || i > 0x1F644) {
            int sym = EMOJI_CODE_TO_SYMBOL(i);
            NSString *emoT = [[NSString alloc] initWithBytes:&sym length:sizeof(sym) encoding:NSUTF8StringEncoding];
            [array addObject:emoT];
        }
    }
    return array;
}


- (void)setupCollectionView{
    
    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize =CGSizeMake(40 * SCREENH6, 40 * SCREENH6);
    layout.sectionInset = UIEdgeInsetsMake(5 * SCREENH6, 5 * SCREENH6, 5 * SCREENH6, 5 * SCREENH6);
    
    //设置collectionView滚动方向
    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //2.初始化collectionView
    UICollectionView * collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kScreenH, kScreenW, 230 * SCREENH6) collectionViewLayout:layout];
    
    collectionView.backgroundColor = ZRWhiteColor;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.pagingEnabled = YES;
    //3.注册collectionViewCell
    //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [collectionView registerClass:[EmojiCollectionViewCell class] forCellWithReuseIdentifier:@"EmojiCollectionViewCell"];
    //4.设置代理
    collectionView.delegate = self;
    collectionView.dataSource = self;
    //    [collectionView setContentOffset:CGPointMake(-30 * SCREENH6, 0)];
    
    self.collectionView = collectionView;
    
    [self.view addSubview:self.collectionView];
}

#pragma mark collectionView代理方法

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.arrEmotion.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    EmojiCollectionViewCell *cell = (EmojiCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"EmojiCollectionViewCell" forIndexPath:indexPath];
    //设置数据
    cell.emojiLabel.text = self.arrEmotion[indexPath.row];
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (!self.inputFuncView.placeHold.hidden) {
        
        self.inputFuncView.placeHold.hidden = YES;
        self.inputFuncView.textViewInput.text = self.arrEmotion[indexPath.row];
    }else{
        
        self.inputFuncView.textViewInput.text = [self.inputFuncView.textViewInput.text stringByAppendingString:self.arrEmotion[indexPath.row]];;
    }
    
    
}


- (void)loadData{
    
    if (self.group_jg_gid) {
        
        [[ZRNetworkTool sharedTool] getGroupMemberBannedAndTouserWithGroup_jg_gid:self.group_jg_gid WithBlock:^(BOOL success, id responseData) {
            
//            NSLog(@"res===%@",responseData);
            if (success) {
                
                NSDictionary * dict = responseData[@"data"];
                
                self.is_banned = [NSString stringWithFormat:@"%@",dict[@"is_banned"]];
            }
        }];
        
        [[ZRNetworkTool sharedTool] getGroupTodayActivityWithGroup_jg_gid:self.group_jg_gid WithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
                NSDictionary * dict = responseData[@"data"];
                
                [self.muDict setValue:dict forKey:@"activity"];
                
                [self updateTopView];
            }
        }];
        
        [[ZRNetworkTool sharedTool] getGroupTodayTopicWithGroup_jg_gid:self.group_jg_gid WithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
                NSDictionary * dict = responseData[@"data"];
                
                [self.muDict setValue:dict forKey:@"topic"];
                
                [self updateTopView];
            }
        }];
    }
    
}


- (void)updateTopView{

    if (self.muDict.allKeys.count == 1) {
        
        self.topBackView.frame = CGRectMake(15 * SCREENH6, topHeight, 345 * SCREENH6, 50 * SCREENH6);
        
        if([[self.muDict allKeys] containsObject:@"activity"]){
            
            self.topImageView.frame = CGRectMake(10 * SCREENH6, 12.5 * SCREENH6, 25 * SCREENH6, 25 * SCREENH6);
            self.topBackButton.frame = CGRectMake(0, 0, 305 * SCREENH6, 50 * SCREENH6);
            self.topCloseButton.frame = CGRectMake(315 * SCREENH6, 15 * SCREENH6, 20 * SCREENH6, 20 * SCREENH6);
            
            NSDictionary * dict = self.muDict[@"activity"];
            NSString * title = [NSString stringWithFormat:@"《%@》",dict[@"activity_title"]];
            NSString * string = [NSString stringWithFormat:@"今日活动:%@感兴趣的小伙伴赶紧加入我们吧。",title];
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range1 = [[str string] rangeOfString:@"今日活动:"];
            [str addAttribute:NSForegroundColorAttributeName value:ZRWhiteColor range:range1];
            NSRange range2 = [[str string] rangeOfString:title];
            [str addAttribute:NSForegroundColorAttributeName value:ColorWithRGB(0xFFF3AE) range:range2];
            NSRange range3 = [[str string] rangeOfString:@"感兴趣的小伙伴赶紧加入我们吧。"];
            [str addAttribute:NSForegroundColorAttributeName value:ZRWhiteColor range:range3];
            
            self.topTitleLabel.attributedText = str;

            CGSize attrStrSize = [self preferredSizeWithMaxWidth:255 * SCREENH6 withLabel:self.topTitleLabel];
            CGFloat labH = attrStrSize.height;
            
            self.topTitleLabel.frame = CGRectMake(45 * SCREENH6, 10 * SCREENH6, 255 * SCREENH6, labH);
            
            self.topTitleLabel.centerY = self.topImageView.centerY;
            
            self.activityID = [NSString stringWithFormat:@"%@",dict[@"id"]];
            
        }else if ([[self.muDict allKeys] containsObject:@"topic"]){
            
            self.bottomBackButton.frame = CGRectMake(0, 0, 305 * SCREENH6, 50 * SCREENH6);
            self.bottomImageView.frame = CGRectMake(10 * SCREENH6, 12.5 * SCREENH6, 25 * SCREENH6, 25 * SCREENH6);
            self.bottomCloseButton.frame = CGRectMake(315 * SCREENH6, 15 * SCREENH6, 20 * SCREENH6, 20 * SCREENH6);
            
            NSDictionary * dict = self.muDict[@"topic"];
            NSString * title = [NSString stringWithFormat:@"#%@#",dict[@"topic_title"]];
            NSString * string = [NSString stringWithFormat:@"今日话题:%@",title];
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range1 = [[str string] rangeOfString:@"今日活动:"];
            [str addAttribute:NSForegroundColorAttributeName value:ZRWhiteColor range:range1];
            NSRange range2 = [[str string] rangeOfString:title];
            [str addAttribute:NSForegroundColorAttributeName value:ColorWithRGB(0xFFF3AE) range:range2];
            
            self.bottomTitleLabel.attributedText = str;
            
            CGSize attrStrSize = [self preferredSizeWithMaxWidth:255 * SCREENH6 withLabel:self.bottomTitleLabel];
            CGFloat labH = attrStrSize.height;
            
            self.bottomTitleLabel.frame = CGRectMake(45 * SCREENH6, 10 * SCREENH6, 255 * SCREENH6, labH);
            
            self.bottomTitleLabel.centerY = self.bottomImageView.centerY;
            
            self.topicID = [NSString stringWithFormat:@"%@",dict[@"id"]];
        }
        
//        self.chatTableView.frame = CGRectMake(0, self.topBackView.bottom, kScreenW, self.view.uu_height- kBarHeight - 40 * SCREENH6 - self.topBackView.bottom);
        
    }else if (self.muDict.allKeys.count == 2){
        
        self.topBackView.frame = CGRectMake(15 * SCREENH6, topHeight, 345 * SCREENH6, 100 * SCREENH6);
        self.topBackButton.frame = CGRectMake(0, 0, 305 * SCREENH6, 50 * SCREENH6);
        self.bottomBackButton.frame = CGRectMake(0, 50 * SCREENH6, 305 * SCREENH6, 50 * SCREENH6);
        
        self.topImageView.frame = CGRectMake(10 * SCREENH6, 12.5 * SCREENH6, 25 * SCREENH6, 25 * SCREENH6);
        self.topCloseButton.frame = CGRectMake(315 * SCREENH6, 15 * SCREENH6, 20 * SCREENH6, 20 * SCREENH6);
        self.bottomImageView.frame = CGRectMake(10 * SCREENH6, 62.5 * SCREENH6, 25 * SCREENH6, 25 * SCREENH6);
        self.bottomCloseButton.frame = CGRectMake(315 * SCREENH6, 65 * SCREENH6, 20 * SCREENH6, 20 * SCREENH6);
        self.lineView.frame = CGRectMake(0 * SCREENH6, 49.5 * SCREENH6, 345 * SCREENH6, 1 * SCREENH6);
        
        NSDictionary * dict = self.muDict[@"activity"];
        NSString * title = [NSString stringWithFormat:@"《%@》",dict[@"activity_title"]];
        NSString * string = [NSString stringWithFormat:@"今日活动:%@感兴趣的小伙伴赶紧加入我们吧。",title];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
        NSRange range1 = [[str string] rangeOfString:@"今日活动:"];
        [str addAttribute:NSForegroundColorAttributeName value:ZRWhiteColor range:range1];
        NSRange range2 = [[str string] rangeOfString:title];
        [str addAttribute:NSForegroundColorAttributeName value:ColorWithRGB(0xFFF3AE) range:range2];
        NSRange range3 = [[str string] rangeOfString:@"感兴趣的小伙伴赶紧加入我们吧。"];
        [str addAttribute:NSForegroundColorAttributeName value:ZRWhiteColor range:range3];
        
        self.topTitleLabel.attributedText = str;
        
        CGSize attrStrSize = [self preferredSizeWithMaxWidth:255 * SCREENH6 withLabel:self.topTitleLabel];
        CGFloat labH = attrStrSize.height;
        
        self.topTitleLabel.frame = CGRectMake(45 * SCREENH6, 10 * SCREENH6, 255 * SCREENH6, labH);
        
        self.topTitleLabel.centerY = self.topImageView.centerY;
        
        NSDictionary * topicDict = self.muDict[@"topic"];
        NSString * topicTitle = [NSString stringWithFormat:@"#%@#",topicDict[@"topic_title"]];
        NSString * topicString = [NSString stringWithFormat:@"今日话题:%@",topicTitle];
        NSMutableAttributedString * topicStr = [[NSMutableAttributedString alloc] initWithString:topicString];
        NSRange topicRange1 = [[topicStr string] rangeOfString:@"今日活动:"];
        [topicStr addAttribute:NSForegroundColorAttributeName value:ZRWhiteColor range:topicRange1];
        NSRange topicRange2 = [[topicStr string] rangeOfString:topicTitle];
        [topicStr addAttribute:NSForegroundColorAttributeName value:ColorWithRGB(0xFFF3AE) range:topicRange2];

        self.bottomTitleLabel.attributedText = topicStr;

        CGSize strSize = [self preferredSizeWithMaxWidth:255 * SCREENH6 withLabel:self.bottomTitleLabel];
        CGFloat Height = strSize.height;

        self.bottomTitleLabel.frame = CGRectMake(45 * SCREENH6, 60 * SCREENH6, 255 * SCREENH6, Height);

        self.bottomTitleLabel.centerY = self.bottomImageView.centerY;
        
        self.activityID = [NSString stringWithFormat:@"%@",dict[@"id"]];
        self.topicID = [NSString stringWithFormat:@"%@",topicDict[@"id"]];
        
//        _chatTableView.frame = CGRectMake(0, self.topBackView.bottom, kScreenW, self.view.uu_height- kBarHeight - 40 * SCREENH6 - self.topBackView.bottom);
        
    }else{
        
        [self.topBackView removeFromSuperview];
        
//        _chatTableView.frame = CGRectMake(0, 0, self.view.uu_width, self.view.uu_height - 40 * SCREENH6 - kBarHeight);
    }
}

- (void)setupNav{
    
    UIButton * rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25 * SCREENH6, 6 * SCREENH6)];
    
    [rightButton setImage:[UIImage imageNamed:@"成员更多"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(didMoreButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.rightButton = rightButton;
    
    UIBarButtonItem * rightBar = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.navigationItem.rightBarButtonItem = rightBar;
    
    int conversationType = self.conversation.conversationType;
    
    if (conversationType == 1) {
        
        JMSGUser *user = self.conversation.target;
        
        [[ZRNetworkTool sharedTool] getUserIdByPhoneWithPhone:user.username WithBlock:^(BOOL success, id responseData) {
            
//            NSLog(@"res===%@",responseData);
            if (success) {
                
                self.user_id = [NSString stringWithFormat:@"%@",responseData[@"data"]];
            }
        }];
        
        [[ZRNetworkTool sharedTool] byPhoneGetIdentityWithPhone:user.username ResultWithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
                int data = [responseData[@"data"] intValue];
                if (data == 1) {
                    //店家
                    UIImageView * shopImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0 , 10 * SCREENH6, 27 * SCREENH6, 14 * SCREENH6)];
                    
                    shopImageView.image = [UIImage imageNamed:@"chatshop"];
                    
                    UILabel * name = [[UILabel alloc] initWithFrame:CGRectMake(shopImageView.right, 7 * SCREENH6, 40 * SCREENH6, 15 * SCREENH6)];
                    
                    name.textColor = ZRBlackColor;
                    name.font = [UIFont systemFontOfSize:15 * SCREENH6];
                    name.textAlignment = NSTextAlignmentCenter;
                    if (user.nickname) {
                        name.text = user.nickname;
                    }else{
                        name.text = self.conversation.title;
                    }
                    [name sizeToFit];
    
                    UIView* titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100 * SCREENH6, 40 * SCREENH6)];
                    
                    titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
                    titleView.autoresizesSubviews = YES;
                    
                    [titleView addSubview:shopImageView];
                    [titleView addSubview:name];
                    
                    self.navigationItem.titleView = titleView;
                }else{
                    //用户
                    if (user.nickname) {
                        self.title = user.nickname;
                    }else{
                        self.title = self.conversation.title;
                    }
                }
            }else{
                
                
            }
            
        }];
        
        
//        self.rightButton.hidden = YES;
        self.chatModel.isGroupChat = NO;
    }else if (conversationType == 2){
        
        JMSGGroup * group = self.conversation.target;
        self.gid = [NSString stringWithFormat:@"%@",group.gid];
        self.title = self.conversation.title;
//        self.rightButton.hidden = NO;
        self.chatModel.isGroupChat = YES;
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //add notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adjustCollectionViewLayout) name:UIDeviceOrientationDidChangeNotification object:nil];
    
	[self tableViewScrollToBottom];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLayoutSubviews
{
	[super viewDidLayoutSubviews];
	
    CGFloat y = 0;
    if (self.topBackView) {
        
        y = self.topBackView.bottom;
    }
    
	if (_inputFuncView.textViewInput.isFirstResponder) {
		_chatTableView.frame = CGRectMake(0, y, self.view.uu_width, self.view.uu_height- 40 * SCREENH6-_keyboardHeight - kBarHeight - y);
		_inputFuncView.frame = CGRectMake(0, _chatTableView.uu_bottom, self.view.uu_width, 40 * SCREENH6);
	} else {
        
        if ([self.showEmjio isEqualToString:@"show"]) {

            _chatTableView.frame = CGRectMake(0, y, self.view.uu_width, self.view.uu_height - 40 * SCREENH6 - kBarHeight - y - 230 * SCREENH6);
            _inputFuncView.frame = CGRectMake(0, _chatTableView.uu_bottom, self.view.uu_width, 40 * SCREENH6);

            if (_chatTableView.contentSize.height > _chatTableView.frame.size.height) {
                
                [_chatTableView setContentOffset:CGPointMake(0, _chatTableView.contentSize.height - _chatTableView.frame.size.height) animated:YES];
            }
            
        }else{

            _chatTableView.frame = CGRectMake(0, y, self.view.uu_width, self.view.uu_height - 40 * SCREENH6 - kBarHeight - y);
           _inputFuncView.frame = CGRectMake(0, _chatTableView.uu_bottom, self.view.uu_width, 40 * SCREENH6);
        }
	}
    
    
}

#pragma mark - prive methods

- (void)initBasicViews
{
	_chatTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.uu_width, self.view.uu_height- kBarHeight - 40 * SCREENH6) style:UITableViewStylePlain];
	_chatTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	_chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	_chatTableView.delegate = self;
	_chatTableView.dataSource = self;
    //创建轻拍手势
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [_chatTableView addGestureRecognizer:tapGR];
    
	[self.view addSubview:_chatTableView];
	
	[_chatTableView registerClass:[UUMessageCell class] forCellReuseIdentifier:NSStringFromClass([UUMessageCell class])];
	
	_inputFuncView = [[UUInputFunctionView alloc] initWithFrame:CGRectMake(0, _chatTableView.uu_bottom, self.view.uu_width, 40 * SCREENH6)];
	_inputFuncView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
	_inputFuncView.delegate = self;
	[self.view addSubview:_inputFuncView];
	
	
	
//    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[@" private ",@" group "]];
//    [segment addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
//    segment.selectedSegmentIndex = 0;
//    self.navigationItem.titleView = segment;
//
//    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:nil action:nil];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:nil action:nil];
}


- (void)addRefreshViews
{
//    __weak typeof(self) weakSelf = self;
//
//    //load more
//    self.pageNum = self.pageNum + 10;
//
//    self.chatTableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
//
//        NSLog(@"self.pageNum===%d",self.pageNum);
//        NSLog(@"dataSource.count===%lu",weakSelf.chatModel.dataSource.count);
//        if (weakSelf.chatModel.dataSource.count > self.pageNum) {
//
//            [weakSelf.chatModel addRandomItemsToDataSource:10];
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:10 inSection:0];
//
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [weakSelf.chatTableView reloadData];
//                [weakSelf.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
//            });
//        }
//        [weakSelf.chatTableView.mj_header endRefreshing];
//    }];
}

- (void)loadBaseViewsAndData
{
    
    self.chatModel = [[ChatModel alloc] init];
    self.chatModel.conversation = self.conversation;
    [self.chatModel populateRandomDataSource];
	
//    [self performSelector:@selector(sss) withObject:nil afterDelay:3.0];
    [self.chatTableView reloadData];
}


//- (void)sss{
//
//
//}

#pragma mark - notification event

//tableView Scroll to bottom
- (void)tableViewScrollToBottom
{
    
	if (self.chatModel.dataSource.count==0) { return; }
	
	NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatModel.dataSource.count-1 inSection:0];
	[self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(void)keyboardChange:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardEndFrame;
    
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
	
	_keyboardHeight = keyboardEndFrame.size.height;
	
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
	
	self.chatTableView.uu_height = self.view.uu_height - _inputFuncView.uu_height;
	self.chatTableView.uu_height -= notification.name == UIKeyboardWillShowNotification ? _keyboardHeight:0;
    self.chatTableView.contentOffset = CGPointMake(0, self.chatTableView.contentSize.height-self.chatTableView.uu_height);

	self.inputFuncView.uu_top = self.chatTableView.uu_bottom;
	
    [UIView commitAnimations];
}

- (void)adjustCollectionViewLayout
{
	[self.chatModel recountFrame];
	[self.chatTableView reloadData];
}

#pragma mark - InputFunctionViewDelegate

- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendMessage:(NSString *)message
{
    if ([self.is_banned isEqualToString:@"1"]) {
        
        funcView.textViewInput.text = @"";
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"你已被群主禁言，暂时无法发言。"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        if (message.length > 0) {
            
            NSString * imgStr = DEF_GET_OBJECT(@"imgStr");
            NSString * name = DEF_GET_OBJECT(@"name");
            
            NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
            
            NSTimeInterval a = [dat timeIntervalSince1970];
            
            NSDate * date  = [NSDate dateWithTimeIntervalSince1970:a];
            
            NSDictionary *dic = @{@"strContent": message,
                                  @"type": @(UUMessageTypeText),
                                  @"strTime": [date description],
                                  @"strIcon":imgStr,
                                  @"strName":name
                                  };
            funcView.textViewInput.text = @"";
            [funcView changeSendBtnWithPhoto:YES];
            [self dealTheFunctionData:dic];
            
            JMSGMessage *messages = nil;
            JMSGTextContent *textContent = [[JMSGTextContent alloc] initWithText:message];
            
            messages = [_conversation createMessageWithContent:textContent];
            
            [self.conversation sendMessage:messages];
            
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"发送内容不能为空"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
    }

}



- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendPicture:(UIImage *)image
{
    
    NSDictionary *dic = @{@"picture": image,
                          @"type": @(UUMessageTypePicture)};
    [self dealTheFunctionData:dic];
    
    JMSGMessage* message = nil;

    JMSGImageContent *imageContent = [[JMSGImageContent alloc] initWithImageData:UIImagePNGRepresentation(image)];
    if (imageContent) {
        
        message = [_conversation createMessageWithContent:imageContent];
    }
}

- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendVoice:(NSData *)voice time:(NSInteger)second
{
    if ([self.is_banned isEqualToString:@"1"]) {
        
        self.inputFuncView.textViewInput.text = @"";
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"你已被群主禁言，暂时无法发言。"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        NSString * imgStr = DEF_GET_OBJECT(@"imgStr");
        NSString * name = DEF_GET_OBJECT(@"name");
        
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        
        NSTimeInterval a = [dat timeIntervalSince1970];
        
        NSDate * date  = [NSDate dateWithTimeIntervalSince1970:a];
        
        NSDictionary *dic = @{@"voice": voice,
                              @"strVoiceTime": [NSString stringWithFormat:@"%d",(int)second],
                              @"type": @(UUMessageTypeVoice),
                              @"strTime": [date description],
                              @"strIcon":imgStr,
                              @"strName":name
                              };
        [self dealTheFunctionData:dic];
        
        JMSGMessage *voiceMessage = nil;
        JMSGVoiceContent *voiceContent = [[JMSGVoiceContent alloc] initWithVoiceData:voice
                                                                       voiceDuration:[NSNumber numberWithInteger:second]];
        
        voiceMessage = [_conversation createMessageWithContent:voiceContent];
        [_conversation sendMessage:voiceMessage];
    }
    
}

- (void)clickEmojiButton{
    
//    KeyboardVC * vc = [KeyboardVC new];
//
//    [self.navigationController pushViewController:vc animated:YES];
     [self.view endEditing:YES];
    if ([self.showEmjio isEqualToString:@"hidden"]) {
        
        self.showEmjio = @"show";
        self.inputFuncView.btnSendMessage.selected = YES;
        [self.inputFuncView.textViewInput resignFirstResponder];
//        self.chatTableView.frame = CGRectMake(0, 0, self.view.uu_width, self.view.uu_height- kBarHeight - 40 * SCREENH6);
        
            // 添加动画
        [UIView animateWithDuration:0.25 animations:^{
            self.chatTableView.height = self.chatTableView.height - 230 * SCREENH6;
//            self.chatTableView.contentOffset = CGPointMake(0, self.chatTableView.contentSize.height-self.chatTableView.uu_height);
//            self.chatTableView.contentOffset = CGPointMake(0, -230 * SCREENH6);
            self.inputFuncView.frame = CGRectMake(0,self.chatTableView.uu_bottom, self.view.uu_width, 40 * SCREENH6);
            self.collectionView.y = self.inputFuncView.uu_bottom;
        }];

    }else if ([self.showEmjio isEqualToString:@"show"]){
        
        self.showEmjio = @"hidden";
        self.inputFuncView.btnSendMessage.selected = NO;
        
        [UIView animateWithDuration:0.25 animations:^{
//            self.chatTableView.contentOffset = CGPointMake(0, 230 * SCREENH6);
//            self.chatTableView.contentInset = UIEdgeInsetsMake(self.chatTableView.contentInset.top, 0, 0, 0);
//            self.chatTableView.contentOffset = CGPointMake(0, self.chatTableView.contentSize.height-self.chatTableView.uu_height);
            self.chatTableView.height = self.chatTableView.height + 230 * SCREENH6;
            self.inputFuncView.y = self.inputFuncView.bottom;
            self.collectionView.y = kScreenH;
        }];
    }
}

//点击输入框
- (void)clickTextView{
    
    self.showEmjio = @"hidden";
    self.inputFuncView.btnSendMessage.selected = NO;
    
    self.collectionView.y = kScreenH;
}

//开始录音
- (void)startVoice{
    
    MainNavigationController * nav = (MainNavigationController *)self.navigationController;
    nav.fullScreenGes.enabled = NO;
}
//取消录音、完成
- (void)stopVoice{
    
    MainNavigationController * nav = (MainNavigationController *)self.navigationController;
    nav.fullScreenGes.enabled = YES;

}

- (void)clickImageButton{
    
    [self.inputFuncView.textViewInput resignFirstResponder];
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        
        self.alertVC.popoverPresentationController.sourceView = self.view;
        self.alertVC.popoverPresentationController.sourceRect = CGRectMake(10 * SCREENH6,kScreenH - 150 * SCREENH6,355 * SCREENH6,150 * SCREENH6);
        //            self.alertVC.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    [self presentViewController:self.alertVC animated:YES completion:nil];
}

//点击发送按钮
- (void)clickSentMessage{
    
    if ([self.is_banned isEqualToString:@"1"]) {
        
        self.inputFuncView.textViewInput.text = @"";
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"你已被群主禁言，暂时无法发言。"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        if (self.inputFuncView.textViewInput.text.length > 0) {
            
            NSString * imgStr = DEF_GET_OBJECT(@"imgStr");
            NSString * name = DEF_GET_OBJECT(@"name");
            
            NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
            
            NSTimeInterval a = [dat timeIntervalSince1970];
            
            NSDate * date  = [NSDate dateWithTimeIntervalSince1970:a];
            
            NSDictionary *dic = @{@"strContent": self.inputFuncView.textViewInput.text,
                                  @"type": @(UUMessageTypeText),
                                  @"strTime": [date description],
                                  @"strIcon":imgStr,
                                  @"strName":name
                                  };
            self.inputFuncView.textViewInput.text = @"";
//            [self.inputFuncView changeSendBtnWithPhoto:YES];
            [self dealTheFunctionData:dic];
            
            JMSGMessage *messages = nil;
            JMSGTextContent *textContent = [[JMSGTextContent alloc] initWithText:self.inputFuncView.textViewInput.text];
            
            messages = [_conversation createMessageWithContent:textContent];
            
            [self.conversation sendMessage:messages];
            
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"发送内容不能为空"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
    }
}


- (void)dealTheFunctionData:(NSDictionary *)dic
{
    [self.chatModel addSpecifiedItem:dic];
    [self.chatTableView reloadData];
	[self tableViewScrollToBottom];
}

#pragma mark - tableView delegate & datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.chatModel.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UUMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UUMessageCell class])];
	cell.delegate = self;
    UUMessageFrame * message = self.chatModel.dataSource[indexPath.row];
    cell.messageFrame = message;
    if (message.message.type == UUMessageTypePicture) {
        
        cell.Jmessage = self.chatModel.jmessageArray[indexPath.row];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.chatModel.dataSource[indexPath.row] cellHeight];
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    [self.view endEditing:YES];
//}
//
//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
//{
//    [self.view endEditing:YES];
//}

#pragma mark - UUMessageCellDelegate

- (void)chatCell:(UUMessageCell *)cell headImageDidClick:(NSString *)userId
{
//    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:cell.messageFrame.message.strName message:@"headImage clicked" delegate:nil cancelButtonTitle:@"sure" otherButtonTitles:nil];
//    [alert show];
}

#pragma mark --add Delegate
- (void)addDelegate {
    [JMessage addDelegate:self withConversation:self.conversation];
}

#pragma mark --收到消息
- (void)onReceiveMessage:(JMSGMessage *)message error:(NSError *)error {

//    NSLog(@"fromType===%@",message.fromType);
//    NSLog(@"msgId===%@",message.msgId);

//    if(message.fromType){
    
        if (error == nil && message) {
            
            NSMutableDictionary * dict = [NSMutableDictionary dictionary];
            
            NSInteger from = message.isReceived;
            NSUInteger contentType = message.contentType;
            contentType = contentType;
            if (contentType == 1) {
                
                JMSGAbstractContent *content = message.content;
                
                JMSGTextContent *textContent = (JMSGTextContent *)content;
                
                [dict setObject:textContent.text forKey:@"strContent"];
            }else if (contentType == 2){
//                self.type = @"reveced";
                [self.chatModel.jmessageArray addObject:message];
                JMSGImageContent *imgContent = (JMSGImageContent *)message.content;
                
//                [imgContent thumbImageData:^(NSData *data, NSString *objectId, NSError *error) {
//
//                    //这里改变RunLoop模式
////                    CFRunLoopStop(CFRunLoopGetMain());
//
//                    if (data == nil || error) {
//
//                        NSLog(@"error===%@",error);
//
//                        return ;
//                    }
//
//                    UIImage * image = [UIImage imageWithData:data];
//
//                    [dict setObject:image forKey:@"picture"];
//                }];
                
                [dict setObject:imgContent forKey:@"image"];

            }else if (contentType == 3){
                
                JMSGVoiceContent *voiceContent = (JMSGVoiceContent *)message.content;
                
//                NSLog(@"voiceContent===%@",voiceContent);
                [dict setObject:voiceContent.duration forKey:@"strVoiceTime"];
//                [dict setObject:voiceContent forKey:@"voiceContent"];
                [voiceContent voiceData:^(NSData *data, NSString *objectId, NSError *error) {
                    //这里改变RunLoop模式
//                    CFRunLoopStop(CFRunLoopGetMain());

                    if (error == nil) {


                        [dict setObject:data forKey:@"voice"];
                    }
                }];
            }
            
            NSString * timeStr = [NSString stringWithFormat:@"%@",message.timestamp];
            NSTimeInterval interval    =[timeStr doubleValue] / 1000.0;
            NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *dateString       = [formatter stringFromDate: date];
            
            JMSGUser * user = message.fromUser;
            
            if (user.nickname) {
                [dict setObject:user.nickname forKey:@"strName"];
            }
            
            [dict setObject:user forKey:@"user"];
            [dict setObject:@(from) forKey:@"from"];
            [dict setObject:@(contentType) forKey:@"type"];
            [dict setObject:dateString forKey:@"strTime"];
            
            [self dealTheFunctionData:dict];
        }
}



- (void)didMoreButton{
    
    HiddenBar;
    
    int conversationType = self.conversation.conversationType;
    if (conversationType == 2) {
        
        GroupInfoViewController * groupVC = [GroupInfoViewController new];
        
        groupVC.group_jg_gid = self.gid;
        
        [self.navigationController pushViewController:groupVC animated:YES];
    }else{
        
        PersonalViewController * personVC = [PersonalViewController new];
        
        personVC.ID = self.user_id;
        
        [self.navigationController pushViewController:personVC animated:YES];
    }
    
}


- (void)setupTopView{

    UIView * topBackView = [UIView new];
    
    topBackView.backgroundColor = ZRBlackColor;
    topBackView.userInteractionEnabled = YES;
    topBackView.layer.cornerRadius = 5 * SCREENH6;
    topBackView.layer.masksToBounds = YES;
    topBackView.userInteractionEnabled = YES;
    
    self.topBackView = topBackView;
    
    [self.view addSubview:self.topBackView];
    
    
    UIImageView * topImageView = [UIImageView new];
    topImageView.image = [UIImage imageNamed:@"社团active"];
    self.topImageView = topImageView;
    [self.topBackView addSubview:self.topImageView];
    UIImageView * bottomImageView = [UIImageView new];
    bottomImageView.image = [UIImage imageNamed:@"社团topic"];
    self.bottomImageView = bottomImageView;
    [self.topBackView addSubview:self.bottomImageView];
    
    UIButton * topBackButton = [UIButton new];
    [topBackButton addTarget:self action:@selector(clickBackButton:) forControlEvents:UIControlEventTouchUpInside];
    self.topBackButton = topBackButton;
    [self.topBackView addSubview:self.topBackButton];
    UIButton * bottomBackButton = [UIButton new];
    [bottomBackButton addTarget:self action:@selector(clickBackButton:) forControlEvents:UIControlEventTouchUpInside];
    self.bottomBackButton = bottomBackButton;
    [self.topBackView addSubview:self.bottomBackButton];
    
    UIButton * topCloseButton = [UIButton new];
    [topCloseButton setImage:[UIImage imageNamed:@"社团关闭"] forState:UIControlStateNormal];
    [topCloseButton addTarget:self action:@selector(clickCloseButton:) forControlEvents:UIControlEventTouchUpInside];
    self.topCloseButton = topCloseButton;
    [self.topBackView addSubview:self.topCloseButton];
    UIButton * bottomCloseButton = [UIButton new];
    [bottomCloseButton setImage:[UIImage imageNamed:@"社团关闭"] forState:UIControlStateNormal];
    [bottomCloseButton addTarget:self action:@selector(clickCloseButton:) forControlEvents:UIControlEventTouchUpInside];
    self.bottomCloseButton = bottomCloseButton;
    [self.topBackView addSubview:self.bottomCloseButton];
    
    UILabel * topTitleLabel = [UILabel new];
    topTitleLabel.textColor = ZRWhiteColor;
    topTitleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    topTitleLabel.numberOfLines = 2;
//    topTitleLabel.text = @"今日活动:";
    self.topTitleLabel = topTitleLabel;
    [self.topBackView addSubview:self.topTitleLabel];
    UILabel * bottomTitleLabel = [UILabel new];
    bottomTitleLabel.textColor = ZRWhiteColor;
    bottomTitleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
//    bottomTitleLabel.text = @"话题活动:";
    bottomTitleLabel.numberOfLines = 2;
    self.bottomTitleLabel = bottomTitleLabel;
    [self.topBackView addSubview:self.bottomTitleLabel];
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0x4D4D4D);
    
    self.lineView = lineView;
    
    [self.topBackView addSubview:self.lineView];
}

- (CGSize)preferredSizeWithMaxWidth:(CGFloat)maxWidth withLabel:(UILabel *)label
{
    
    CGSize size = [label sizeThatFits:CGSizeMake(maxWidth, 10000000.0f)];
    size.width = fmin(size.width, maxWidth); //在numberOfLine为1模式下返回的可能会比maxWidth大，所以这里我们限制下
    return size;
}

- (void)clickCloseButton:(UIButton *)button{
    
    if (button == self.topCloseButton) {
        
        [self.muDict removeObjectForKey:@"activity"];
        
        [self.topBackView removeFromSuperview];
        [self setupTopView];
    }else if (button == self.bottomCloseButton){
        
        [self.muDict removeObjectForKey:@"topic"];
    }
    
    [self updateTopView];
}


- (void)clickBackButton:(UIButton *)button{
    HiddenBar;
    if (button == self.topBackButton) {
        
        GroupActiveDetailViewController * activeVC = [GroupActiveDetailViewController new];
        
        activeVC.ID =self.activityID;
        
        [self.navigationController pushViewController:activeVC animated:YES];
        
    }else if (button == self.bottomBackButton){
        
        TopicDetailViewController * topicVC = [TopicDetailViewController new];
        
        topicVC.ID = self.topicID;
        
        [self.navigationController pushViewController:topicVC animated:YES];
    }
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}


#pragma mark -实现图片选择器代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

    if ([self.is_banned isEqualToString:@"1"]) {
        
        self.inputFuncView.textViewInput.text = @"";
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"你已被群主禁言，暂时无法发言。"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
       
        NSString * imgStr = DEF_GET_OBJECT(@"imgStr");
        NSString * name = DEF_GET_OBJECT(@"name");
        
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        
        NSTimeInterval a = [dat timeIntervalSince1970];
        
        NSDate * date  = [NSDate dateWithTimeIntervalSince1970:a];
        
        NSDictionary *dic = @{@"picture": image,
                              @"type": @(UUMessageTypePicture),
                              @"strTime": [date description],
                              @"strIcon":imgStr,
                              @"strName":name
                              };
        
        [self dealTheFunctionData:dic];
        
        JMSGMessage* message = nil;
        NSData *frontImageData = UIImageJPEGRepresentation(image,0.3);//UIImagePNGRepresentation(image)
        JMSGImageContent *imageContent = [[JMSGImageContent alloc] initWithImageData:frontImageData];
        if (imageContent) {
            
            message = [_conversation createMessageWithContent:imageContent];
            
            [self.chatModel.jmessageArray addObject:message];
        }
        
        [self.conversation sendMessage:message];
    }
    
}

//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

- (void)tapAction{
    
    [self.inputFuncView.textViewInput resignFirstResponder];
    
    if ([self.showEmjio isEqualToString:@"show"]) {
        
        self.showEmjio = @"hidden";
        self.inputFuncView.btnSendMessage.selected = NO;
        // 添加动画
        [UIView animateWithDuration:0.25 animations:^{
            
            self.chatTableView.frame = CGRectMake(0, 0, self.view.uu_width, self.view.uu_height- kBarHeight - 40 * SCREENH6);
            self.inputFuncView.y = self.chatTableView.uu_bottom;
            self.collectionView.y = kScreenH;
        }];
    }
}

#pragma mark - TableView 占位图
- (NSString *)xy_noDataViewMessage {
    
    return @"";
}

@end
